<?
function callback($buffer){
	$str		= array(chr(9), chr(10));
	$buffer	= str_replace($str, "", $buffer);
	return $buffer;
}

function check_email_address($email) {
	//First, we check that there's one @ symbol, and that the lengths are right
	if(!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)){
		//Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
		return false;
	}
	//Split it into sections to make life easier
	$email_array = explode("@", $email);
	$local_array = explode(".", $email_array[0]);
	for($i = 0; $i < sizeof($local_array); $i++){
		if(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])){
			return false;
		}
	}
	if(!ereg("^\[?[0-9\.]+\]?$", $email_array[1])){
	//Check if domain is IP. If not, it should be valid domain name
		$domain_array = explode(".", $email_array[1]);
		if(sizeof($domain_array) < 2){
			return false; // Not enough parts to domain
		}
		for($i = 0; $i < sizeof($domain_array); $i++){
			if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])){
				return false;
			}
		}
	}
	return true;
}

function check_session_security($security_code){
	$return = 1;
	if(!isset($_SESSION["session_security_code"])) $_SESSION["session_security_code"] = generate_security_code();
	if($security_code != $_SESSION["session_security_code"]){
		$return = 0;
	}
	// Reset lại session security code
	$_SESSION["session_security_code"] = generate_security_code();
	return $return;
}

function cut_string($str, $length, $char=" ..."){
	//Nếu chuỗi cần cắt nhỏ hơn $length thì return luôn
	$strlen	= mb_strlen($str, "UTF-8");
	if($strlen <= $length) return $str;
	
	//Cắt chiều dài chuỗi $str tới đoạn cần lấy
	$substr	= mb_substr($str, 0, $length, "UTF-8");
	if(mb_substr($str, $length, 1, "UTF-8") == " ") return $substr . $char;
	
	//Xác định dấu " " cuối cùng trong chuỗi $substr vừa cắt
	$strPoint= mb_strrpos($substr, " ", "UTF-8");
	
	//Return string
	if($strPoint < $length - 20) return $substr . $char;
	else return mb_substr($substr, 0, $strPoint, "UTF-8") . $char;
}

function format_number($number, $edit=0){
	if($edit == 0){
		$return	= number_format($number, 2, ".", ",");
		if(intval(substr($return, -2, 2)) == 0) $return = number_format($number, 0, ".", ",");
		elseif(intval(substr($return, -1, 1)) == 0) $return = number_format($number, 1, ".", ",");
		return $return;
	}
	else{
		$return	= number_format($number, 2, ".", "");
		if(intval(substr($return, -2, 2)) == 0) $return = number_format($number, 0, ".", "");
		return $return;
	}
}

function generate_array_variable($variable){
	$list			= tdt($variable);
	$arrTemp		= explode("{-break-}", $list);
	$arrReturn	= array();
	for($i=0; $i<count($arrTemp); $i++) $arrReturn[$i] = trim($arrTemp[$i]);
	return $arrReturn;
}

function generate_security_code(){
	$code	= rand(1000, 9999);
	return $code;
}

function getURL($serverName=0, $scriptName=0, $fileName=1, $queryString=1, $varDenied=''){
	//$url	 = '';
//	$slash = '/';
//	if($scriptName != 0)$slash	= "";
//	if($serverName != 0){
//		if(isset($_SERVER['SERVER_NAME'])){
//			$url .= 'http://' . $_SERVER['SERVER_NAME'];
//			if(isset($_SERVER['SERVER_PORT'])) $url .= ":" . $_SERVER['SERVER_PORT'];
//			$url .= $slash;
//		}
//	}
//	if($scriptName != 0){
//		if(isset($_SERVER['SCRIPT_NAME']))	$url .= substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/') + 1);
//	}
//	if($fileName	!= 0){
//		if(isset($_SERVER['SCRIPT_NAME']))	$url .= substr($_SERVER['SCRIPT_NAME'], strrpos($_SERVER['SCRIPT_NAME'], '/') + 1);
//	}
//	if($queryString!= 0){
//		$url .= '?';
//		reset($_GET);
//		$i = 0;
//		if($varDenied != ''){
//			$arrVarDenied = explode('|', $varDenied);
//			while(list($k, $v) = each($_GET)){
//				if(array_search($k, $arrVarDenied) === false){
//					$i++;
//					if($i > 1) $url .= '&' . $k . '=' . @urlencode($v);
//					else $url .= $k . '=' . @urlencode($v);
//				}
//			}
//		}
//		else{
//			while(list($k, $v) = each($_GET)){
//				$i++;
//				if($i > 1) $url .= '&' . $k . '=' . @urlencode($v);
//				else $url .= $k . '=' . @urlencode($v);
//			}
//		}
//	}
//	$url = str_replace('"', '&quot;', strval($url));
//	return $url;
}

function getValue($value_name, $data_type = "int", $method = "GET", $default_value = 0, $advance = 0){
	$value = $default_value;
	switch($method){
		case "GET": if(isset($_GET[$value_name])) $value = $_GET[$value_name]; break;
		case "POST": if(isset($_POST[$value_name])) $value = $_POST[$value_name]; break;
		case "COOKIE": if(isset($_COOKIE[$value_name])) $value = $_COOKIE[$value_name]; break;
		case "SESSION": if(isset($_SESSION[$value_name])) $value = $_SESSION[$value_name]; break;
		default: if(isset($_GET[$value_name])) $value = $_GET[$value_name]; break;
	}
	$valueArray	= array("int" => intval($value), "str" => trim(strval($value)), "flo" => floatval($value), "dbl" => doubleval($value), "arr" => $value);
	foreach($valueArray as $key => $returnValue){
		if($data_type == $key){
			if($advance != 0){
				switch($advance){
					case 1:
						$returnValue = replaceMQ($returnValue);
						break;
					case 2:
						$returnValue = htmlspecialbo($returnValue);
						break;
				}
			}
			//Do số quá lớn nên phải kiểm tra trước khi trả về giá trị
			if((strval($returnValue) == "INF") && ($data_type != "str")) return 0;
			return $returnValue;
			break;
		}
	}
	return (intval($value));
}

function htmlspecialbo($str){
	$arrDenied	= array('<', '>', '\"', '"');
	$arrReplace	= array('&lt;', '&gt;', '&quot;', '&quot;');
	$str = str_replace($arrDenied, $arrReplace, $str);
	return $str;
}


function microtime_float(){
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}

function random(){
	$rand_value = "";
	$rand_value.= rand(1000,9999);
	$rand_value.= chr(rand(65,90));
	$rand_value.= rand(1000,9999);
	$rand_value.= chr(rand(97,122));
	$rand_value.= rand(1000,9999);
	$rand_value.= chr(rand(97,122));
	$rand_value.= rand(1000,9999);
	return $rand_value;
}

function redirect($url){
	$url	= htmlspecialbo($url);
	echo '<script type="text/javascript">window.location.href = "' . $url . '";</script>';
	exit();
}

function RemoveSign($str)
{
    $coDau=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă",
    "ằ","ắ","ặ","ẳ","ẵ",
    "è","é","ẹ","ẻ","ẽ","ê","ề" ,"ế","ệ","ể","ễ",
    "ì","í","ị","ỉ","ĩ",
    "ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
    ,"ờ","ớ","ợ","ở","ỡ",
    "ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
    "ỳ","ý","ỵ","ỷ","ỹ",
    "đ",
    "À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
    ,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
    "È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
    "Ì","Í","Ị","Ỉ","Ĩ",
    "Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
    ,"Ờ","Ớ","Ợ","Ở","Ỡ",
    "Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
    "Ỳ","Ý","Ỵ","Ỷ","Ỹ",
    "Đ","ê","ù","à");

    $khongDau=array("a","a","a","a","a","a","a","a","a","a","a"
    ,"a","a","a","a","a","a",
    "e","e","e","e","e","e","e","e","e","e","e",
    "i","i","i","i","i",
    "o","o","o","o","o","o","o","o","o","o","o","o"
    ,"o","o","o","o","o",
    "u","u","u","u","u","u","u","u","u","u","u",
    "y","y","y","y","y",
    "d",
    "A","A","A","A","A","A","A","A","A","A","A","A"
    ,"A","A","A","A","A",
    "E","E","E","E","E","E","E","E","E","E","E",
    "I","I","I","I","I",
    "O","O","O","O","O","O","O","O","O","O","O","O"
    ,"O","O","O","O","O",
    "U","U","U","U","U","U","U","U","U","U","U",
    "Y","Y","Y","Y","Y",
    "D","e","u","a");
    return str_replace($coDau,$khongDau,$str);
}

function removeAccent($mystring){
	$marTViet=array(
		// Chữ thường
		"à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă","ằ","ắ","ặ","ẳ","ẵ",
		"è","é","ẹ","ẻ","ẽ","ê","ề","ế","ệ","ể","ễ",
		"ì","í","ị","ỉ","ĩ",
		"ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ","ờ","ớ","ợ","ở","ỡ",
		"ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
		"ỳ","ý","ỵ","ỷ","ỹ",
		"đ","Đ","'",
		// Chữ hoa
		"À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă","Ằ","Ắ","Ặ","Ẳ","Ẵ",
		"È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
		"Ì","Í","Ị","Ỉ","Ĩ",
		"Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ","Ờ","Ớ","Ợ","Ở","Ỡ",
		"Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
		"Ỳ","Ý","Ỵ","Ỷ","Ỹ",
		"Đ","Đ","'"
		);
	$marKoDau=array(
		/// Chữ thường
		"a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a",
		"e","e","e","e","e","e","e","e","e","e","e",
		"i","i","i","i","i",
		"o","o","o","o","o","o","o","o","o","o","o","o","o","o","o","o","o",
		"u","u","u","u","u","u","u","u","u","u","u",
		"y","y","y","y","y",
		"d","D","",
		//Chữ hoa
		"A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A",
		"E","E","E","E","E","E","E","E","E","E","E",
		"I","I","I","I","I",
		"O","O","O","O","O","O","O","O","O","O","O","O","O","O","O","O","O",
		"U","U","U","U","U","U","U","U","U","U","U",
		"Y","Y","Y","Y","Y",
		"D","D","",
		);
	return str_replace($marTViet, $marKoDau, $mystring);
}

function removeHTML($string){
	$string = preg_replace ('/<script.*?\>.*?<\/script>/si', ' ', $string); 
	$string = preg_replace ('/<style.*?\>.*?<\/style>/si', ' ', $string); 
	$string = preg_replace ('/<.*?\>/si', ' ', $string); 
	$string = str_replace ('&nbsp;', ' ', $string);
	return $string;
}

function removeLink($string){
	$string = preg_replace ('/<a.*?\>/si', '', $string);
	$string = preg_replace ('/<\/a>/si', '', $string);
	return $string;
}

function removeScript($string){
	$string = preg_replace ('/<script.*?\>.*?<\/script>/si', '<br />', $string);
	$string = preg_replace ('/on([a-zA-Z]*)=".*?"/si', ' ', $string);
	$string = preg_replace ('/On([a-zA-Z]*)=".*?"/si', ' ', $string);
	$string = preg_replace ("/on([a-zA-Z]*)='.*?'/si", " ", $string);
	$string = preg_replace ("/On([a-zA-Z]*)='.*?'/si", " ", $string);
	return $string; 
}

function replaceFCK($string, $type=0){
	$array_fck	= array ("&Agrave;", "&Aacute;", "&Acirc;", "&Atilde;", "&Egrave;", "&Eacute;", "&Ecirc;", "&Igrave;", "&Iacute;", "&Icirc;",
								"&Iuml;", "&ETH;", "&Ograve;", "&Oacute;", "&Ocirc;", "&Otilde;", "&Ugrave;", "&Uacute;", "&Yacute;", "&agrave;",
								"&aacute;", "&acirc;", "&atilde;", "&egrave;", "&eacute;", "&ecirc;", "&igrave;", "&iacute;", "&ograve;", "&oacute;",
								"&ocirc;", "&otilde;", "&ugrave;", "&uacute;", "&ucirc;", "&yacute;",
								);
	$array_text	= array ("À", "Á", "Â", "Ã", "È", "É", "Ê", "Ì", "Í", "Î",
								"Ï", "Ð", "Ò", "Ó", "Ô", "Õ", "Ù", "Ú", "Ý", "à",
								"á", "â", "ã", "è", "é", "ê", "ì", "í", "ò", "ó",
								"ô", "õ", "ù", "ú", "û", "ý",
								);
	if($type == 1) $string = str_replace($array_fck, $array_text, $string);
	else $string = str_replace($array_text, $array_fck, $string);
	return $string;
}

function replaceJS($text){
	$arr_str = array("\'", "'", '"', "&#39", "&#39;", chr(10), chr(13), "\n");
	$arr_rep = array(" ", " ", '&quot;', " ", " ", " ", " ");
	$text		= str_replace($arr_str, $arr_rep, $text);
	$text		= str_replace("    ", " ", $text);
	$text		= str_replace("   ", " ", $text);
	$text		= str_replace("  ", " ", $text);
	return $text;
}

function replace_keyword_search($keyword, $lower=1){
	if($lower == 1) $keyword	= mb_strtolower($keyword, "UTF-8");
	$keyword	= replaceMQ($keyword);
	$arrRep	= array("'", '"', "-", "+", "=", "*", "?", "/", "!", "~", "#", "@", "%", "$", "^", "&", "(", ")", ";", ":", "\\", ".", ",", "[", "]", "{", "}", "‘", "’", '“', '”');
	$keyword	= str_replace($arrRep, " ", $keyword);
	$keyword	= str_replace("  ", " ", $keyword);
	$keyword	= str_replace("  ", " ", $keyword);
	return $keyword;
}

function replaceMQ($text){
	$text	= str_replace("\'", "'", $text);
	$text	= str_replace("'", "''", $text);
	return $text;
}

function remove_magic_quote($str){
	$str = str_replace("\'", "'", $str);
	$str = str_replace("\&quot;", "&quot;", $str);
	$str = str_replace("\\\\", "\\", $str);
	return $str;
}

function tdt($variable){
	global $lang_display;
	if (isset($lang_display[$variable])){
		if (trim($lang_display[$variable]) == ""){
			return "#" . $variable . "#";
		}
		else{
			$arrStr	= array("\\\\'", '\"');
			$arrRep	= array("\\'", '"');
			return str_replace($arrStr, $arrRep, $lang_display[$variable]);
		}
	}
	else{
		return "_@" . $variable . "@_";
	}
}

//Function lấy html của 1 url truyền vào
function getcontent($url, $post = "", $refer = "", $usecookie = false) {
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	
	if($post) {
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt ($curl, CURLOPT_POSTFIELDS, $post);
	}
	
	if($refer) {
		curl_setopt($curl, CURLOPT_REFERER,$refer);
	}
	
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3"); 
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	//curl_setopt($curl, CURLOPT_TIMEOUT_MS, 5000);
	
	if ($usecookie) { 
		curl_setopt($curl, CURLOPT_COOKIEJAR, $usecookie); 
		curl_setopt($curl, CURLOPT_COOKIEFILE, $usecookie);    
	}
	
	curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); 
	
	$html = curl_exec($curl);
	curl_close($curl);
	return $html;
}
function get_image($url, $path){
	$filename	=	generate_name($url);
	
	$filePath	= $path . $filename;
	
	$ch	=	curl_init($url);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3");	
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	$result	=	curl_exec($ch);
	curl_close($ch);  
	$fp	=	fopen($filePath,'w+');
	fwrite($fp, $result);
	fclose($fp);
	
	return $filename;
}
//lấy ảnh về server web
function get_image_fer($url, $path){
	$filename	=	generate_name($url);
	
	$filePath	= $path . $filename;
	
	$ch	=	curl_init($url);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3");	
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	$result	=	curl_exec($ch);
	curl_close($ch);  
	$fp	=	fopen($filePath,'w+');
	fwrite($fp, $result);
	fclose($fp);
	
	return $filename;
}


function generate_keyword($str = ""){
	$keyword			=	"";
	
	$arr_special	=	array("(", ")", ".", ",", "|", "'", "\"", "'", "-", "/", "_", "\\", "“", "”");
	$str				=	str_replace($arr_special, " ", $str);
	for($i = 1; $i <= 15; $i++){
		$str			=	str_replace("  ", " ", $str);
	}
	
	$str				=	trim($str);
	$str_kodau		=	removeAccent($str);
	
	$keyword			=	$str	. " " . $str_kodau;
	
	$keyword			=	str_replace(" ", ", ", $keyword);
	
	return  $keyword;
}

function save_log_info($filename, $content){
	$break_line		=	"---------------------------------------------------------------------------";
	$log_path     =   $_SERVER["DOCUMENT_ROOT"] . "/logs/";
	$handle       =   @fopen($log_path . $filename . ".cfn", "a");
	//Neu handle chua co mo thêm ../
	if (!$handle) $handle = @fopen($log_path . $filename . ".cfn", "a");
	//Neu ko mo dc lan 2 thi exit luon
	if (!$handle) exit();		
	fwrite($handle, date("d/m/Y h:i:s A") . " " . @$_SERVER["REQUEST_URI"] . PHP_EOL . $content . PHP_EOL . PHP_EOL . $break_line . PHP_EOL . PHP_EOL);	
	fclose($handle);
}

function getlinks($link, $root = ""){
	$link_return	=	$link;
	if(substr($link, 0, 4) != "http"){
		$link			=	str_replace("..", "", $link);
		$link_return =	$root . $link;
	}
	return $link_return;
}

/**
* Format duraction video
* @param $duraction kieu int
* @return string format 01:08:06
*/
function formatDuraction($duration){
   $formated = '00:00';
   if($duration == 0)
      return $formated;
   else{
      $hours = floor($duration/3600);
      $minutes = floor(($duration / 60) % 60);
      $seconds = $duration % 60;
      if($hours > 0){
         $hours = ($hours > 9) ? $hours . ':' : '0'.$hours . ':';
      }else{
         $hours = '';
      }
      if($minutes > 0){
         $minutes = ($minutes > 9) ? $minutes . ':' : '0'.$minutes . ':';
      }else{
         $hours = '00';
      }
      if($seconds > 0){
         $seconds = ($seconds > 9) ? $seconds : '0'.$seconds;
      }else{
         $seconds = '00';
      }
      $formated = $hours . $minutes .$seconds;
   }
   return $formated;
        
}

/**
* Thay the mot so ky tu trong chuoi
* @param $string video name
* @return string replaced
*/
function handelVidName($string){
   $vidName = '';
   
   $mixsearch = array();
   $mixsearch[0] = 'karaoke';
   $mixsearch[1] = '';
   $mixsearch[2] = '_';
   $mixsearch[3] = '+';
   $mixsearch[4] = "'";
   $mixreplace = array();
   $mixreplace[0] = '';
   $mixreplace[1] = ' ';
   $mixreplace[2] = ' ';
   $mixreplace[3] = ' ';
   $mixreplace[4] = "\\'";
   
   $patterns = array();
   $patterns[0] = '/\([a-z0-9A-Z]+\)/';
   $patterns[1] = '/\[[a-z0-9A-Z]+\]/';
   $replacements = '';
   $replacements = array();
   $replacements[0] = '';
   $replacements[1] = '';
   $vidName = preg_replace($patterns, $replacements, $string);
   $vidName = str_ireplace($mixsearch,$mixreplace,$vidName);
   $vidName = trim($vidName);
   return $vidName;
}
function handleNameImage($string){
   $search = 'hqdefault';
   $replace = 'mqdefault';
   $return = str_replace($search,$replace,$string);
   return $return;
}

function get_http_response_code($url) {
       $headers = get_headers($url);
       return substr($headers[0], 9, 3);
   }
   
/**
 * Pagination function
 * 
 * @param int $current The current page
 * @param int $pages   How many pages there are in total
 * @param int $link    Link format (sprintf with one %d parameter)
 * @return array An array of links
 */
function pagination($current, $pages, $link='?page=%d') {
  $min = ($current-3<$pages && $current-3>0) ? $current-3 : 1;
  $max = ($current+3>$pages) ? $pages : $current+3;
  $output = array();
  for($i=$min; $i<=$max; $i++):
    if($current == $i):
      $output[] = "<span class='page-current'>{$i}</span>";
    else:
      $output[] = '<a href="'.sprintf($link,$i).'">'.$i.'</a>';
    endif;
  endfor;
  if ($current+1 < $pages):
    $output[] = '<a href="'.sprintf($link,$current+1).'">Sau</a>';
  endif;
  if ($current-1 > 0):
    array_unshift($output, '<a href="'.sprintf($link,$current-1).'">Trước</a>');
  endif;
  return $output;
}

function echoArray($array){
   if(!is_array($array)){
      echo 'sai kiểu';
      return;
   }
   if(!empty($array)){
      echo '<pre>';
      print_r($array);
      echo '</pre>';
   }else{
      echo 'Mảng rỗng';
   }
}

?>